﻿namespace Deppton.Mobile.Services
{
    using System;
    using System.IO;
    using Deppton.Model;
    using System.Collections.Generic;

    public class SurveyDefinitionStorageService : ISurveyDefinitionStorageService
    {
        private static string SurveysDefinitionsStoragePath
        {
            get
            {
                // It is much more comfortable when testing surveys and its definition to share
                // a folder in your hard drive with the mobile device emulator and edit the
                // files from the host machine.
                // If you want to do so uncomment the following line.
                // Remember that there is a similar one in the SurveysStorageService class.
                //// return Path.Combine(PathUtilities.GetStorageCardPath(), "surveyDefinitions");

                return Path.Combine(PathUtilities.GetExecutionPath(), "surveyDefinitions");
            }
        }

        private IServicesPortfolio servicesPortfolio;

        public IServicesPortfolio ServicesPortfolio
        {
            set
            {
                this.servicesPortfolio = value;
            }
        }

        public SurveyDefinition RetrieveSurveyDefinition(string surveyDefinitionId)
        {
            return FilesystemHelpers.SurveyDefinitionFilesystemHandler.LoadFromFile(
                Path.Combine(SurveysDefinitionsStoragePath, string.Format("{0}.xml", surveyDefinitionId)));
        }

        public ICollection<SurveyDefinition> RetrieveAllSurveyDefinitions()
        {
            var surveyDefinitions = new List<SurveyDefinition>();

            foreach (var xmlFile in Directory.GetFiles(SurveysDefinitionsStoragePath, "*.xml"))
            {
                surveyDefinitions.Add(FilesystemHelpers.SurveyDefinitionFilesystemHandler.LoadFromFile(xmlFile));
            }

            return surveyDefinitions;
        }
    }
}
